﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
using DBControl;
using System.Data;
using System.Configuration;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace SellerProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string appKey = "12167888";
                string appSecret = "sandbox3606eac16f68e582b5b5e52ba";
                if (VerifyTopResponse(Request.QueryString["top_parameters"], Request.QueryString["top_session"], Request.QueryString["top_sign"], appKey, appSecret))
                {
                    SystemLib sl = new SystemLib();
                    string usernick = sl.GetParameters(Request.QueryString["top_parameters"], "visitor_nick");
                    Session.Add("user", usernick);
                    SaveUserSession(usernick, Request.QueryString["top_session"]);
                    
                    //bindgrid(appKey, appSecret, Request.QueryString["top_session"]);
                }
                else
                {
                    
                }
            }
        }

        /// <summary>
        /// 验证回调地址的签名是否合法。
        /// </summary>
        /// <param name="topParams">TOP私有参数（未经Base64解密后的）</param>
        /// <param name="topSession">TOP私有会话码</param>
        /// <param name="topSign">TOP回调签名（经过URL反编码的）</param>
        /// <param name="appKey">应用公钥</param>
        /// <param name="appSecret">应用密钥</param>
        /// <returns>验证成功返回True，否则返回False</returns>
        private bool VerifyTopResponse(string topParams, string topSession, string topSign, string appKey, string appSecret)
        {
            StringBuilder result = new StringBuilder();
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            result.Append(appKey).Append(topParams).Append(topSession).Append(appSecret);
            byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));

            return System.Convert.ToBase64String(bytes) == topSign;
        }

        private void SaveUserSession(string userNick,string SessionKey)
        {
            SqlDbHelper sdh = new SqlDbHelper(this.ConnString());
            string selectSql = "SELECT * FROM UserSession WHERE UserName='" + userNick + "'";
            DataTable dt = sdh.ExecuteDataTable(selectSql);
            if (dt.Rows.Count > 0)
            {
                string updateSql = "UPDATE UserSession SET SessionKey = '"+ SessionKey +"',UpdateTime='"+ DateTime.Now +"' WHERE UserName='"+ userNick +"'";
                sdh.ExecuteNonQuery(updateSql);
            }
            else
            {
                string insertSql = "INSERT INTO UserSession(UserName,SessionKey) VALUES('" + userNick + "','" + SessionKey + "')";
                sdh.ExecuteNonQuery(insertSql);
            }
        }

        private void bindgrid(string akey, string aSecret,string userNick)
        {
            ITopClient itop = new DefaultTopClient("http://gw.api.tbsandbox.com/router/rest", akey, aSecret);
            ItemGetRequest itemget = new ItemGetRequest();
            itemget.NumIid = 6000190936;
            itemget.Nick = Session["user"].ToString();
            itemget.Fields = "title,nick,type,skus,props_name,promoted_service,cid,props,input_pids,input_str,desc,pic_url,stuff_status,location,price,post_fee,express_fee,ems_fee,freight_payer";
            ItemGetResponse itemresponse = itop.Execute(itemget, userNick);
            
            //this.Mylist.DataSource = itemresponse.Items;
            //this.Mylist.DataBind();
        }

        private string ConnString()
        {
            SystemLib sl = new SystemLib();
            string connStr = "";
            string datasource = ConfigurationManager.AppSettings["SqlServer"];
            string dataname = ConfigurationManager.AppSettings["SqlDataName"];
            string uid = ConfigurationManager.AppSettings["SqlUid"];
            string pwd = sl.Decrypto(ConfigurationManager.AppSettings["SqlPwd"]);
            connStr = "Data Source=" + datasource + ";Initial Catalog=" + dataname + ";User ID=" + uid + ";PassWord=" + pwd;
            return connStr;
        }

        protected void myview_DataBound(object sender, EventArgs e)
        {
            
        }

        private void bindForm()
        {
            string appKey = "12167888";
            string appSecret = "sandbox3606eac16f68e582b5b5e52ba";
            ITopClient itop = new DefaultTopClient("http://gw.api.tbsandbox.com/router/rest", appKey, appSecret);
            ItempropsGetRequest itemprop = new ItempropsGetRequest();
            itemprop.Cid = 50010518;
            itemprop.Fields = "pid, name, must, multi, prop_values,is_key_prop,is_color_prop";
            ItempropsGetResponse itempropResponse = itop.Execute(itemprop);
            Panel mypan = new Panel();
            mypan.ID = "mainDiv";
            for (int i = 0; i < itempropResponse.ItemProps.Count; i++)
            {
                if (itempropResponse.ItemProps[i].IsColorProp || itempropResponse.ItemProps[i].IsKeyProp)
                {
                    Panel panel = new Panel();
                    Label lb = new Label();
                    lb.Text = itempropResponse.ItemProps[i].Name;
                    panel.Controls.Add(lb);
                    if (!itempropResponse.ItemProps[i].Multi)
                    {
                        DropDownList droplist = new DropDownList();
                        for (int j = 0; j < itempropResponse.ItemProps[i].PropValues.Count; j++)
                        {
                            ListItem li = new ListItem();
                            li.Text = itempropResponse.ItemProps[i].PropValues[j].Name;
                            li.Value = itempropResponse.ItemProps[i].PropValues[j].Vid.ToString();
                            droplist.Items.Add(li);
                        }

                        panel.Controls.Add(droplist);
                        mypan.Controls.Add(panel);
                    }
                    else
                    {
                        CheckBoxList chklist = new CheckBoxList();
                        //chklist.RepeatDirection = RepeatDirection.Horizontal;
                        chklist.RepeatColumns = 5;
                        for (int k = 0; k < itempropResponse.ItemProps[i].PropValues.Count; k++)
                        {
                            ListItem chkitem = new ListItem();
                            chkitem.Text = itempropResponse.ItemProps[i].PropValues[k].Name;
                            chkitem.Value = itempropResponse.ItemProps[i].PropValues[k].Vid.ToString();
                            chklist.Items.Add(chkitem);
                        }
                        panel.Controls.Add(chklist);
                        mypan.Controls.Add(panel);
                    }
                }
            }
            mainform.Controls.Add(mypan);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string appKey = "12167888";
            string appSecret = "sandbox3606eac16f68e582b5b5e52ba";
            ITopClient itop = new DefaultTopClient("http://gw.api.tbsandbox.com/router/rest", appKey, appSecret);
            ItemGetRequest itemget = new ItemGetRequest();

            itemget.NumIid = 6000190936;
            itemget.Nick = Session["user"].ToString();
            itemget.Fields = "title,nick,type,skus,props_name,promoted_service,cid,props,input_pids,input_str,desc,pic_url,stuff_status,location,price,post_fee,express_fee,ems_fee,freight_payer,approve_status";
            //itemget.Fields = "title,nick,approve_status";
            ItemGetResponse itemresponse = itop.Execute(itemget);

            //ItemUpdateDelistingRequest itemDelist = new ItemUpdateDelistingRequest();
            //itemDelist.NumIid = itemresponse.Item.NumIid;
            //ItemUpdateDelistingResponse idelist = itop.Execute(itemDelist);

            ItemAddRequest itemadd = new ItemAddRequest();
            itemadd.Num = 1;
            itemadd.Price = itemresponse.Item.Price;
            itemadd.Type = itemresponse.Item.Type;
            itemadd.StuffStatus = itemresponse.Item.StuffStatus;
            itemadd.Cid = itemresponse.Item.Cid;
            itemadd.Title = itemresponse.Item.Title + "123" + DateTime.Now.ToShortTimeString();
            itemadd.Desc = itemresponse.Item.Desc;
            itemadd.LocationState = itemresponse.Item.Location.State;
            itemadd.LocationCity = itemresponse.Item.Location.City;
            itemadd.Props = itemresponse.Item.Props;
            
            //itemadd.ListTime = DateTime.Parse("2011-03-28 12:32:00");
            itemadd.IsTaobao = true;
            //itemadd.IsEx = true;
            ItemAddResponse itemaddResponse = itop.Execute(itemadd, Request.QueryString["top_session"]);
            if (itemaddResponse.IsError)
            {
                Response.Write(itemaddResponse.ErrMsg);
            }
        }

        private bool validateUser()
        {
            string appkey = SystemLib.appkey;
            string appsecret = SystemLib.appsecret;
            string appurl = SystemLib.appurl;
            bool result = false;

            ITopClient itop = new DefaultTopClient(appurl, appkey, appsecret);


            return result;
        }






    }
}